<template>
  <div class="recording-controls">
    <div class="mb-3">
      <p class="text-sm font-semibold text-gray-700 mb-3">录制控制</p>
      
      <!-- 录制URL输入 -->
      <div class="mb-4">
        <el-input
          v-model="recordingUrl"
          placeholder="请输入要录制的网页URL"
          :disabled="isRecording"
          size="default"
          class="advanced-url-input"
        >
          <template #prefix>
            <el-icon class="text-blue-500"><i-ep-link /></el-icon>
          </template>
        </el-input>
      </div>

             <!-- 录制按钮 -->
             <div class="grid grid-cols-1 gap-2">
               <el-button
                 type="primary"
                 size="default"
                 :loading="recordingStatus === 'starting' || recordingStatus === 'stopping'"
                 :disabled="!recordingUrl && !isRecording"
                 @click="handleRecordingClick"
                 class="premium-button primary-button h-12 text-sm font-medium"
                 :class="isRecording ? 'recording-active' : 'recording-inactive'"
               >
          <el-icon class="mr-2 text-base">
            <i-ep-video-camera v-if="!isRecording" />
            <i-ep-video-pause v-else />
          </el-icon>
          {{ isRecording ? '停止录制' : '开始录制' }}
        </el-button>

        <!-- 录制状态显示 -->
        <div 
          v-if="isRecording"
          class="recording-status bg-red-50 border border-red-200 rounded-md p-2 text-sm"
        >
          <div class="flex items-center text-red-600">
            <div class="recording-dot mr-2"></div>
            <span class="font-medium">
              正在Playwright录制... ({{ recordingSteps.length }} 个步骤)
            </span>
          </div>
          <div v-if="sessionId" class="text-xs text-red-500 mt-1">
            会话ID: {{ sessionId.substring(0, 8) }}...
          </div>
          <div class="text-xs text-blue-600 mt-1">
            Playwright浏览器已启动，请在浏览器中操作
          </div>
        </div>

        <!-- 录制结果预览 -->
        <div 
          v-if="hasRecordingResult && !isRecording"
          class="recording-result bg-green-50 border border-green-200 rounded-md p-2 text-sm"
        >
          <div class="flex items-center justify-between">
            <div class="text-green-600">
              <i class="fas fa-check-circle mr-1"></i>
              录制完成
            </div>
            <el-button 
              size="small" 
              type="primary" 
              text
              @click="importRecordingResult"
            >
              导入步骤
            </el-button>
          </div>
          <div class="text-xs text-green-600 mt-1">
            {{ recordingSteps.length }} 个步骤
          </div>
        </div>

        <!-- 错误显示 -->
        <div 
          v-if="recordingError"
          class="recording-error bg-red-50 border border-red-200 rounded-md p-2 text-sm text-red-600"
        >
          <i class="fas fa-exclamation-triangle mr-1"></i>
          {{ recordingError }}
        </div>


      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRecordingStore } from '../stores/recording'
import { useScriptStore } from '../stores/script'
import { ElMessage } from 'element-plus'

// Element Plus 图标
import { 
  Link as iEpLink,
  VideoCamera as iEpVideoCamera,
  VideoPause as iEpVideoPause,
  Refresh as iEpRefresh,
  Search as iEpSearch
} from '@element-plus/icons-vue'

const recordingStore = useRecordingStore()
const scriptStore = useScriptStore()

// 响应式数据
const recordingUrl = ref('https://www.baidu.com')
const recordingError = ref('')
const recordingStatus = ref('ready') // ready, starting, recording, stopping
const showCleanupButton = ref(false)

// 计算属性
const isRecording = computed(() => recordingStore.isRecording)
const sessionId = computed(() => recordingStore.currentSession?.id)
const recordingSteps = computed(() => recordingStore.recordingSteps)
const hasRecordingResult = computed(() => recordingStore.hasRecordedSteps)
const recordingMode = computed(() => recordingStore.currentSession?.mode || 'simulation')

// 处理录制按钮点击
const handleRecordingClick = async () => {
  if (isRecording.value) {
    await stopRecording()
  } else {
    await startRecording()
  }
}

// 开始录制
const startRecording = async () => {
  try {
    recordingError.value = ''
    recordingStatus.value = 'starting'
    
    const result = await recordingStore.startRecording({
      startUrl: recordingUrl.value,
      name: `录制会话 ${new Date().toLocaleString()}`
    })
    
    if (result.success) {
      recordingStatus.value = 'recording'
      
      ElMessage.success({
        message: 'Playwright录制已启动！浏览器即将自动打开，请在其中进行操作。',
        duration: 4000
      })
      
      showCleanupButton.value = false
    } else {
      recordingStatus.value = 'ready'
      recordingError.value = result.error || '开始录制失败'
      ElMessage.error(recordingError.value)
    }
  } catch (error) {
    recordingStatus.value = 'ready'
    recordingError.value = error.message
    ElMessage.error('开始录制失败: ' + error.message)
  }
}

// 停止录制
const stopRecording = async () => {
  try {
    recordingStatus.value = 'stopping'
    
    const result = await recordingStore.stopRecording()
    if (result.success) {
      recordingStatus.value = 'ready'
      
      ElMessage.success(`录制完成！已获取Playwright录制结果。\n共录制 ${result.steps.length} 个步骤`)
      
      // 自动导入生成的脚本
      if (result.script) {
        await autoImportGeneratedScript(result.script)
      }
      
      showCleanupButton.value = true
    } else {
      recordingStatus.value = 'recording'
      ElMessage.error('停止录制失败: ' + (result.error || '未知错误'))
    }
  } catch (error) {
    recordingStatus.value = 'recording'
    ElMessage.error('停止录制失败: ' + error.message)
  }
}

// 自动导入生成的脚本
const autoImportGeneratedScript = async (scriptContent) => {
  try {
    console.log('自动导入生成的脚本...')
    
    // 使用脚本管理器导入脚本
    const { scriptManager } = await import('../services/scriptManager.js')
    const result = await scriptManager.autoImportGeneratedScript(scriptContent)
    
    if (result.success) {
      console.log('脚本自动导入成功')
      
      // 直接使用解析后的步骤更新脚本store
      if (result.steps && result.steps.length > 0) {
        // 清空现有步骤
        if (scriptStore.clearSteps) {
          scriptStore.clearSteps()
        }
        
        // 添加新步骤
        result.steps.forEach(step => {
          const scriptStep = {
            stepNumber: step.stepNumber || step.index + 1,
            type: step.type,
            action: step.action,
            description: step.description || step.name,
            selector: step.selector,
            value: step.value,
            url: step.url,
            timestamp: step.timestamp || new Date().toISOString(),
            status: 'pending'
          }
          
          if (scriptStore.addStep) {
            scriptStore.addStep(scriptStep)
          }
        })
        
        ElMessage.success(`脚本自动导入成功！共导入 ${result.steps.length} 个步骤`)
      }
    } else {
      ElMessage.error('自动导入脚本失败: ' + result.error)
    }
  } catch (error) {
    console.error('自动导入脚本失败:', error)
    ElMessage.error('自动导入脚本失败: ' + error.message)
  }
}

// 诊断录制问题
const diagnoseRecording = async () => {
  try {
    ElMessage.info('正在诊断录制问题...')
    
    // 直接使用 recordingManager 进行诊断
    const { recordingManager } = await import('../services/recordingManager.js')
    
    // 获取录制状态
    const status = recordingManager.getRecordingStatus()
    const session = recordingManager.recordingSession
    
    // 获取录制步骤
    const steps = recordingManager.getRecordedSteps()
    
    // 生成诊断结果
    const diagnosis = {
      recordingMode: session?.mode || 'unknown',
      isRecording: status.isRecording,
      stepCount: status.stepCount,
      steps: steps.slice(0, 3) // 只显示前3个步骤
    }
    
    // 显示诊断结果
    ElMessage({
      type: 'success',
      message: '诊断完成！录制功能正常',
      duration: 5000
    })
    
    // 在控制台显示详细诊断信息
    console.log('录制问题诊断结果:')
    console.log('- 录制模式:', diagnosis.recordingMode)
    console.log('- 是否正在录制:', diagnosis.isRecording)
    console.log('- 步骤数量:', diagnosis.stepCount)
    console.log('- 前3个步骤:', diagnosis.steps)
    
  } catch (error) {
    console.error('诊断失败:', error)
    ElMessage.error('诊断失败: ' + error.message)
  }
}

// 清理录制状态
const cleanupRecording = () => {
  recordingStore.cleanup()
  recordingError.value = ''
  recordingStatus.value = 'ready'
  showCleanupButton.value = false
  ElMessage.info('录制状态已清理')
}

const importRecordingResult = () => {
  const steps = recordingStore.recordingSteps
  if (steps.length === 0) {
    ElMessage.warning('没有可导入的录制结果')
    return
  }
  
  try {
    // 清空现有步骤并添加新步骤
    if (scriptStore.clearSteps) {
      scriptStore.clearSteps()
    }
    
    steps.forEach(step => {
      // 转换录制步骤格式为脚本步骤格式
      const scriptStep = {
        stepNumber: step.stepNumber,
        type: step.type,
        action: step.action,
        description: step.description,
        selector: step.selector,
        value: step.value,
        url: step.url,
        timestamp: step.timestamp,
        status: 'pending'
      }
      
      if (scriptStore.addStep) {
        scriptStore.addStep(scriptStep)
      }
    })
    
    ElMessage.success(`成功导入 ${steps.length} 个录制步骤`)
    
    // 重置录制状态
    recordingStore.reset()
    showCleanupButton.value = false
  } catch (error) {
    ElMessage.error('导入录制结果失败: ' + error.message)
  }
}

// 事件监听器
let recordingStatusListener = null
let recordingSessionRestoredListener = null
let recordingCleanedUpListener = null

onMounted(() => {
  // 监听录制状态更新事件
  recordingStatusListener = (event) => {
    const { stepCount } = event.detail
    console.log(`录制状态更新: ${stepCount} 个步骤`)
  }
  
  // 监听录制会话恢复事件
  recordingSessionRestoredListener = (event) => {
    const { sessionId, recordingUrl: restoredUrl } = event.detail
    console.log('录制会话已恢复:', sessionId)
    
    if (restoredUrl) {
      recordingUrl.value = restoredUrl
    }
    
    // 显示恢复提示
    setTimeout(() => {
      ElMessage({
        type: 'warning',
        message: '检测到之前的录制会话，是否继续录制？',
        showClose: true,
        duration: 0,
        customClass: 'recording-restore-message'
      })
    }, 1000)
  }
  
  // 监听录制清理事件
  recordingCleanedUpListener = () => {
    recordingStatus.value = 'ready'
    showCleanupButton.value = false
  }
  
  // 添加事件监听器
  if (typeof window !== 'undefined') {
    window.addEventListener('recordingStatusUpdated', recordingStatusListener)
    window.addEventListener('recordingSessionRestored', recordingSessionRestoredListener)
    window.addEventListener('recordingCleanedUp', recordingCleanedUpListener)
  }
  
  // 初始化录制服务
  import('../services/recordingService.js').then(({ recordingService }) => {
    recordingService.init()
  })
})

onUnmounted(() => {
  // 移除事件监听器
  if (typeof window !== 'undefined') {
    window.removeEventListener('recordingStatusUpdated', recordingStatusListener)
    window.removeEventListener('recordingSessionRestored', recordingSessionRestoredListener)
    window.removeEventListener('recordingCleanedUp', recordingCleanedUpListener)
  }
})
</script>

<style scoped>
.recording-btn {
  width: 100%;
  transition: all 0.3s ease;
}

.recording-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ef4444;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.recording-status {
  animation: fadeIn 0.3s ease-in-out;
}

.recording-result {
  animation: slideIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { 
    opacity: 0; 
    transform: translateY(-10px);
  }
  to { 
    opacity: 1; 
    transform: translateY(0);
  }
}

/* 录制按钮特殊样式 */
.recording-btn.bg-red-50 {
  color: #dc2626;
  border-color: #fca5a5;
}

.recording-btn.bg-red-50:hover {
  background-color: #fef2f2;
  border-color: #f87171;
}

/* 录制中状态 - 使用红色主题 */
.recording-active {
  @apply bg-gradient-to-r from-red-500 to-red-600;
  @apply border-red-500 text-white;
  @apply hover:from-red-600 hover:to-red-700;
  @apply hover:border-red-600;
  @apply shadow-red-500/25 hover:shadow-red-500/40;
  @apply animate-pulse;
}

.recording-active:hover {
  @apply shadow-2xl;
  box-shadow: 0 20px 25px -5px rgba(239, 68, 68, 0.4), 0 10px 10px -5px rgba(239, 68, 68, 0.2);
}

/* 录制待机状态 - 使用与保存按钮一致的蓝色主题 */
.recording-inactive {
  @apply bg-gradient-to-r from-blue-500 to-blue-600;
  @apply border-blue-500 text-white;
  @apply hover:from-blue-600 hover:to-blue-700;
  @apply hover:border-blue-600;
  @apply shadow-blue-500/25 hover:shadow-blue-500/40;
}

.recording-inactive:hover {
  @apply shadow-2xl;
  box-shadow: 0 20px 25px -5px rgba(59, 130, 246, 0.4), 0 10px 10px -5px rgba(59, 130, 246, 0.2);
}

/* 高级URL输入框样式 */
.advanced-url-input {
  @apply h-12;
}

.advanced-url-input :deep(.el-input__wrapper) {
  @apply h-12 rounded-xl border-2 border-gray-200;
  @apply shadow-sm hover:shadow-md;
  @apply transition-all duration-200;
  @apply focus-within:border-blue-500 focus-within:shadow-lg;
  @apply focus-within:shadow-blue-500/20;
}

.advanced-url-input :deep(.el-input__inner) {
  @apply text-sm font-medium;
  @apply placeholder:text-gray-400;
}

.advanced-url-input :deep(.el-input__prefix) {
  @apply pl-4;
}

.advanced-url-input :deep(.el-input__suffix) {
  @apply pr-4;
}

.recording-btn.bg-red-500 {
  background-color: #ef4444;
  border-color: #ef4444;
  color: white;
}

.recording-btn.bg-red-500:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}
</style>